package it.fuesi.synoutils.services.tasks.filestation;

import android.content.Context;
import android.util.Log;

import com.squareup.okhttp.Cache;

import java.util.Set;

import it.fuesi.synoutils.activities.MainActivity;
import it.fuesi.synoutils.fragments.FileStationFragment;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.model.base.ErrorObject;
import it.fuesi.synoutils.model.base.VoidDataObject;
import it.fuesi.synoutils.model.base.VoidResponse;
import it.fuesi.synoutils.model.filestation.FileCopyMoveStartResponse;
import it.fuesi.synoutils.model.filestation.FileCopyMoveStatusResponse;
import it.fuesi.synoutils.model.filestation.FileStationClientParameters;
import it.fuesi.synoutils.services.cache.CacheService;
import it.fuesi.synoutils.services.client.FileStationClient;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class MoveFile extends BaseTask<VoidResponse, VoidDataObject, FileStationClientParameters> {

    private static final String TAG = MoveFile.class.getName();

    public MoveFile(Context context){
        super(context);
    }


    private FileStationClientParameters params;

    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public VoidResponse run(FileStationClientParameters params)  throws Exception{
            this.params = params;
            VoidResponse resp = new VoidResponse();
            resp.setSuccess(true);

            publishProgress("Start moving files");
            final Set<String> files = params.getFilePathList();
            final String dest = params.getFolder_path();
            boolean overwrite = false;
            boolean remove_src = true;

            FileStationClient client = ServiceClientFactory.getClient(FileStationClient.class);

            Log.d(TAG, "Start copy/move files: " + files.size() +" to folder " + dest + " overwrite["+overwrite+"] - remove_src["+remove_src+"]");

            String sources = "";
            for(String file : files){
                sources += FormatHelper.urlEncode(file) + ",";
            }
            sources = sources.substring(0, sources.length()-1);

            FileCopyMoveStartResponse startResponse = client.startCopyMove(sources, FormatHelper.urlEncode(dest), remove_src, overwrite);



            if(startResponse.isSuccess()){
                final String taskId = startResponse.getData().getTaskid();



                boolean stop = false;
                int retry = 0;

                while(!stop && retry < 3) {

                    FileCopyMoveStatusResponse statusResponse = client.statusCopyMove(taskId);
                    if (statusResponse.isSuccess()) {
                        if(statusResponse.getData().isFinished()) stop = true;
                        else{
                            publishProgress("Moving files: " + statusResponse.getData().getProgress() + "%");
                        }
                    }else
                        retry++;
                }

                if(retry >= 3){
                    resp.setSuccess(false);
                    resp.setError(new ErrorObject());
                    resp.getError().setMessage("Error retrieving moving status, too many retries");
                }


            }else {
                resp.setSuccess(false);
                resp.setError(startResponse.getError());
            }

            return resp;


    }

    @Override
    protected void onPostExecute(VoidResponse voidResponse) {
        super.onPostExecute(voidResponse);

        if(voidResponse != null && voidResponse.isSuccess()){
            final String firstFile = params.getFilePathList().iterator().next();
            final String sourceFolder = firstFile.substring(0, firstFile.lastIndexOf("/"));
            CacheService.expireCache(getContext(), FileStationList.CACHE_KEY_PREFIX + sourceFolder);
            MainActivity activity = (MainActivity)getContext();
            FileStationFragment frag = (FileStationFragment)activity.getCurrentFragment();
            frag.doneMoving(true);
        }
    }
}
